<?php

namespace app\api\controller\v1;

use addons\litestore\model\Litestoregoodsspec;
use addons\litestore\model\Wxlitestoregoods;
use app\admin\model\litestore\Litestoregoods;
use app\admin\model\litestore\Litestorenews;
use app\admin\model\Profitorder;
use app\admin\model\Profitorderundo;
use app\admin\model\Profitvip;
use app\api\service\ProfitService;
use app\common\controller\Api;
use think\Db;
use think\Exception;

/**
 */
class Profit extends Api
{
    protected $noNeedLogin = ['doUnprofit'];
    protected $noNeedRight = ['*'];


    public function userAccount()
    {

        $user = $this->auth->getUser();
        $uid = $user['id'];

        $profitService = new ProfitService();
        $amount = $profitService->userProfit($uid);
        $this->success('', $amount);

    }


    /**
     * 我的代理收益
     */
    public function myVipProfit()
    {

        $page = $this->request->param('page');
        $date = $this->request->param('date');
        $startToday = strtotime($date . " 00:00:00");
        $endToday = strtotime($date . " 23:59:59");
        $user = $this->auth->getUser();

        $where = array();
        $where['uid'] = $user['id'];
        $profitVipModel = new Profitvip();
        $limit = 10;
        $offset = ($page - 1) * $limit;
        $list = $profitVipModel->with(['user', 'order'])->where('Profitvip.createtime', '>=', $startToday)
            ->where('Profitvip.createtime', "<=", $endToday)
            ->where($where)->limit($offset, $limit)
            ->select();
        foreach ($list as $key => $val) {
            $val['user']->hidden(['password', 'salt']);
            $list[$key]['username'] = $val['user']['username'];
            $list[$key]['goods_name'] = $val['order']['goods_name'];
            $list[$key]['price'] = $val['order']['goods_price'];
            $list[$key]['total'] = 1;

            $list[$key]['createtime'] = date('Y-m-d H:i:s', $val['createtime']);
            if ($val['type'] == 1) {
                $list[$key]['typeText'] = '礼包购买[直推]';
            } else if ($val['type' == 2]) {
                $list[$key]['typeText'] = '礼包购买[间推]';
            } else if ($val['type'] == 3) {
                $list[$key]['typeText'] = '礼包购买[团队]';
            }
        }
        $this->success('', $list);
    }

    /**
     * 商品销售利润
     */
    public function myProductProfit()
    {


        $page = $this->request->param('page');
        $date = $this->request->param('date');

        if (!$page) $page = 1;

        $user = $this->auth->getUser();
        $where = "";

        if ($date) {
            error_log("======date======" . $date);
            $startToday = strtotime($date . " 00:00:00");
            $endToday = strtotime($date . " 23:59:59");
            $where .= " and o.createtime >= " . $startToday . " and o.createtime <= " . $endToday;
        }
        error_log("==page==" . $page);

        $profitOrderModel = new Profitorder();
        $limit = 10;
        $offset = ($page - 1) * $limit;

        error_log("==where==" . $where);


        $sql = "select username, o.id,og.id, uid,orderId,amount,ratio,o.createtime,type,goods_name,order_id,SUM(total_price) as price,count(og.id) as total from u_profit_order o left join u_user u on o.uid = o.uid left join u_litestore_order_goods og  on o.orderId = og.order_id where o.uid = " . $user['id'] . $where . " GROUP BY orderId limit " . $offset . " ,10";
        error_log("==sql==" . $sql);
        $list = $profitOrderModel->query($sql);
        foreach ($list as $key => $val) {
            $list[$key]['createtime'] = date('Y-m-d', $val['createtime']);
            if ($val['type'] == 'self') {
                $list[$key]['typeText'] = '零售差价';
            } else if ($val['type' == 'team']) {
                $list[$key]['typeText'] = '下单费';
            }
        }
        $this->success('', $list);
    }


    /**
     * 待结算处理
     */
    public function doUnprofit()
    {

        $startToday2 = strtotime(date("Y-m-d") . " 01:00:00");
        $endToday2 = strtotime(date("Y-m-d") . " 04:00:00");


        $time = time();
        if (($time >= $startToday2 && $time <= $endToday2)) {
            $undoProfitModel = new Profitorderundo();
            $list = $undoProfitModel->order('createtime', 'desc')->limit(10)->select();
            Db::startTrans();
            try {

                $orderProfitModel = new Profitorder();

                foreach ($list as $key => $val) {

                    $timediff = time() - $val['createtime'];
                    $days = intval($timediff / 86400);
                    if ($days >= 7) {
                        $db = array();
                        $db['uid'] = $val['uid'];
                        $db['orderId'] = $val['orderId'];
                        $db['amount'] = $val['amount'];
                        $db['ratio'] = $val['ratio'];
                        $db['createtime'] = time();
                        $db['type'] = $val['type'];
                        $db['mark'] = $val['mark'];
                        $orderProfitModel->insert($db);
                        $undoProfitModel->where('id',$val['id'])->delete();
                    }

                }
                Db::commit();

            } catch (Exception $e) {
                echo $e->getMessage();
                Db::rollback();
                return FALSE;
            }
        }



    }


}
